#!/usr/bin/env python

import sys
from os.path import splitext
import Image
import random

PATTERN_SIZE = 60 # how big will the repeating pattern be

if (len(sys.argv) < 2):
    sys.exit("Usage: mkstereogram.py <depth map image>")

# initialization: opening images, making random pattern {{{
depth_map_img = Image.open(sys.argv[1])
depth_map = depth_map_img.load()

res_img = Image.new("RGB", depth_map_img.size)
res = res_img.load()

pattern_img = Image.new("RGB", (PATTERN_SIZE, depth_map_img.size[1]))
pattern = pattern_img.load()

for x in xrange(0, PATTERN_SIZE, 2):
    for y in xrange(0, depth_map_img.size[1], 2):
        #pattern_img.paste((int(random.random()*255), int(random.random()*255),
        #                int(random.random()*255)), (x, y, x+2, y+2));
        pattern_img.paste((20+int(random.random()*80), 20+int(random.random()*80),
                        int(random.random()*255)), (x, y, x+2, y+2));
# }}}

# the stereogram itself {{{

# first blit the repeating pattern
x = 0
while (x < res_img.size[0]):
    y = 0
    while (y < res_img.size[1]):
        res_img.paste(pattern_img, (x, y, x+PATTERN_SIZE,
                                    y+depth_map_img.size[1]))
        y += depth_map_img.size[1]
    x += PATTERN_SIZE

# then shift using the depth map
for x in xrange(res_img.size[0]):
    for y in xrange(res_img.size[1]):
        shift = int(depth_map[x,y][0] / 25.5)*2
        res[x-shift,y], res[x,y] = res[x,y], res[x-shift,y]
# }}}

# finish off
res_img.save(splitext(sys.argv[1])[0]+"-stereogram"+splitext(sys.argv[1])[1])
res_img.show()
